import { ref } from 'vue';

import { formatChartTooltip, formatUnit } from '@/utils/format'
import { basiclineOption, buildLineSeriesData } from '@/utils/chartOption';
import { cloneDeep, map, forEach } from 'lodash'
import { getExceptionChartsData, queryReceiverPackageLine, querySendPackageLine, querySessionCountLine, queryZeroWindowLine } from '@/api/exceptionDetail';
export default function useRequestTab({detailInfo:detailData, props}) {
  const appChartLoading = ref(false);
  const appChartsOptions = ref({
    reqChartOptions: basiclineOption,
    errChartOptions: basiclineOption,
    resChartOptions: basiclineOption,
  });
  const netChartLoading = ref(false);
  const netChartsOptions = ref({
    packetLoss: basiclineOption,
    retransmit: basiclineOption,
    rttsum: basiclineOption,
    zeroWindow: basiclineOption,
    sessionCount: basiclineOption,
    sendPackage: basiclineOption,
    receiverPackage: basiclineOption,
  });
  // 构造请求量、错误率和响应时间折线图信息
  const buildChartData = (data, name, unit, showTitle = false) => {
    const chartOptions = cloneDeep(basiclineOption);
    if (data.length) {
      chartOptions.xAxis[0].data = map(data, "time");
      chartOptions.yAxis[0].axisLabel.formatter = (v) => formatUnit(v, unit);
      chartOptions.series.push(buildLineSeriesData(name, map(data, "value")));
      chartOptions.tooltip.formatter = (params) =>
        formatChartTooltip(params, unit);
      if (showTitle) {
        chartOptions.title.show = true;
        chartOptions.title.text = name;
      }
    }
    return chartOptions;
  };
  // 获取应用指标折线图数据
  const getAppChartsData = () => {
    appChartLoading.value = true;
    const detailInfo = detailData.value
    const listParams = props.listParams
    const maxSize = props.maxSize
    const params = {
      startPage: 1,
      size: maxSize,
      startTime: listParams.startTime,
      endTime: listParams.endTime,
      masterIps: listParams.masterIps,
      srcWorkloadList: [
        {
          masterIp: detailInfo?.srcMasterip?.key || "",
          namespace: detailInfo?.srcNamespace || "",
          workloadKind: detailInfo?.srcWorkloadKind || "",
          workloadName: detailInfo?.srcWorkloadName || "",
        },
      ],
      dstWorkloadName: detailInfo?.dstWorkloadName,
      dstNamespace: detailInfo?.dstNamespace,
      dstWorkloadKind: detailInfo?.dstWorkloadKind,
      contentKey: detailInfo?.contentKey,
    };
    if (!detailInfo?.contentKey) {
      params.dstPort = detailInfo?.dstPort;
      params.dstIP = detailInfo?.dstIP?.substring(
        0,
        detailInfo?.dstIP?.indexOf(":")
      );
    }
    getExceptionChartsData(params)
      .then((res) => {
        const { errorRate, requestTotal, responseTime } = res.data;
        appChartsOptions.value = {
          reqChartOptions: buildChartData(
            requestTotal || [],
            "请求量",
            "",
            true
          ),
          errChartOptions: buildChartData(
            errorRate || [],
            "错误率",
            "100%",
            true
          ),
          resChartOptions: buildChartData(
            responseTime || [],
            "响应时间",
            "ns",
            true
          ),
        };
      })
      .finally(() => {
        appChartLoading.value = false;
      });
  };

  // 获取网络指标折现图
  const getNetChartsData = async () => {
    netChartLoading.value = true;
    const detailInfo = detailData.value
    const listParams = props.listParams
    const maxSize = props.maxSize
    console.log(maxSize, 'maxSize in props');
    const params = {
      startPage: 1,
      size: maxSize,
      startTime: listParams.startTime,
      endTime: listParams.endTime,
      masterIps: listParams.masterIps,
      srcWorkloadList: [
        {
          masterIp: detailInfo?.srcMasterip?.key || "",
          namespace: detailInfo?.srcNamespace || "",
          workloadKind: detailInfo?.srcWorkloadKind || "",
          workloadName: detailInfo?.srcWorkloadName || "",
        },
      ],
      dstWorkloadName: detailInfo?.dstWorkloadName,
      dstNamespace: detailInfo?.dstNamespace,
      dstWorkloadKind: detailInfo?.dstWorkloadKind,
    };
    const netParams = {
      dstMasterIp: detailInfo?.dstMasterip?.key || "",
      dstNamespace: detailInfo?.dstNamespace || "",
      dstWorkloadKind: detailInfo?.dstWorkloadKind || "",
      dstWorkloadName: detailInfo?.dstWorkloadName || "",
      from: listParams.startTime,
      to: listParams.endTime,
      srcWorkloadList: [
        {
          masterIp: detailInfo?.srcMasterip?.key || "",
          namespace: detailInfo?.srcNamespace || "",
          workloadKind: detailInfo?.srcWorkloadKind || "",
          workloadName: detailInfo?.srcWorkloadName || "",
        },
      ],
    };
    const queryList = [
      getExceptionChartsData(params),
      querySessionCountLine(netParams, "workload"),
    ];
    if (
      !(
        detailInfo?.srcWorkloadKind === "vm" &&
        detailInfo.dstWorkloadKind === "vm"
      )
    ) {
      queryList.push(
        queryZeroWindowLine(netParams, "workload"),
        querySendPackageLine(netParams, "workload"),
        queryReceiverPackageLine(netParams, "workload")
      );
    }
    const results = await Promise.all(queryList);
    const [res, scRes, zwRes, spcRes, rpcRes] = results;

    const { packetLoss, retransmit, rttsum } = res.data;
    netChartsOptions.value = ({
      packetLoss: buildChartData(packetLoss || [], "丢包数", "", true),
      retransmit: buildChartData(retransmit || [], "重传数", "", true),
      rttsum: buildChartData(rttsum || [], "SRTT", "us", true),
      zeroWindow: zwRes
        ? buildChartData(
            zwRes.data?.lineChartVos || [],
            "0窗口",
            "",
            true
          )
        : cloneDeep(basiclineOption),
      sessionCount: buildChartData(
        scRes.data?.lineChartVos || [],
        "活跃会话数",
        "",
        true
      ),
      sendPackage: spcRes
        ? buildChartData(spcRes.data?.lineChartVos || [], "发包数", "", true)
        : cloneDeep(basiclineOption),
      receiverPackage: rpcRes
        ? buildChartData(rpcRes.data?.lineChartVos || [], "收包数", "", true)
        : cloneDeep(basiclineOption),
    });
    netChartLoading.value = false;
  };
  return {
    appChartLoading,
    appChartsOptions,
    netChartLoading,
    netChartsOptions,
    getAppChartsData,
    getNetChartsData
  }
}
